package hikari.gui.panels.camera;

import com.gooddies.swing.JpDialog;
import com.gooddies.wiring.Wiring;
import com.gooddies.wiring.annotations.PostWiring;
import com.gooddies.wiring.annotations.WiringComponent;
import hikari.gui.MainWindow;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.HeadlessException;

/**
 * @author sad
 */
@WiringComponent
public class CameraPreviewWindow extends JpDialog {

    private Canvas canvas;
    private long hwnd = -1;
    private static final int BASE_WIDTH = 300;

    public CameraPreviewWindow() throws HeadlessException {
        super(Wiring.getComponent(MainWindow.class));
    }

    @PostWiring
    private void init() {
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        canvas = new Canvas();
        canvas.setPreferredSize(new Dimension(BASE_WIDTH, BASE_WIDTH));
        getContentPane().add(canvas);
        setResizable(true);
    }

    public void setAspectRatio(float ratio) {
        int width = canvas.getWidth();
        if (width == 0) {
            width = 150;
        }
        int height = (int) (width / ratio);
        canvas.setPreferredSize(new Dimension(width, height));
        pack();
    }

    public long getHWND() {
        if (hwnd == -1) {
            hwnd = getInternalHWND();
        }
        return hwnd;
    }

    @SuppressWarnings(value = "deprecation")
    private long getInternalHWND() {
        try {
            Class cl = Class.forName("sun.awt.windows.WComponentPeer");
            java.lang.reflect.Field f = cl.getDeclaredField("hwnd");
            f.setAccessible(true);
            return f.getLong(canvas.getPeer());
        } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
            System.err.println("Fatal Error:");
            return -1;
        }
    }

    @Override
    public String getDialogName() {
        return "cameraPreviewDialog";
    }
}
